const removeBatchUrl = "../batchDelete/";
const listRegisterUrl = "../register/list/";
const downloadUrl = "../download/";
const getRegisterUrl = "../register/";
const deleteMetadataByIdUrl = "../deleteMetadataById/"
const updateRegisterUrl = "../register/update/";
const queryRegisterUrl = "../register/query/";
const changeValidateUrl = "../register/changeValidate/"
const succeedCode = 0;
let common;
let $;
let toast
layui.use(['table', 'form', 'jquery', 'common', 'toast'], function () {
    let table = layui.table;
    let form = layui.form;
    $ = layui.jquery;
    common = layui.common;
    toast = layui.toast;


    let cols = [
        [{
            type: 'checkbox'
        },
            {
                title: 'ID',
                field: 'cid',
                align: 'center',
            },
            {
                title: 'Coverage id',
                field: 'coverageId',
                align: 'center'
            },
            {
                title: 'Subtype',
                field: 'subtype',
                align: 'center',
            },
            {
                title: 'Description',
                field: 'description',
                align: 'center'
            },
            {
                title: 'Validate',
                field: 'validate',
                align: 'center',
                templet: '#validate-enable'
            },
            {
                title: 'Create time',
                field: 'createTime',
                align: 'center',
                templet: '#user-createTime'
            },
            {
                title: '操作',
                toolbar: '#user-bar',
                align: 'center',
                width: 130,
                fixed: 'right'
            }
        ]
    ]

    table.render({
        elem: '#user-table',
        url: listRegisterUrl,
        request: {
            pageName: 'current',//页码的参数名称，默认：page
            limitName: 'size' //每页数据量的参数名，默认：limit
        },
        response: {
            countName: 'total' //规定数据总数的字段名称，默认：count
        },
        page: true,
        cols: cols,
        skin: 'line',
        toolbar: '#user-toolbar',
        defaultToolbar: [{
            title: '刷新',
            layEvent: 'refresh',
            icon: 'layui-icon-refresh',
        }, 'filter', 'print', 'exports']
    });

    table.on('tool(user-table)', function (obj) {
        if (obj.event === 'remove') {
            remove(obj);
        } else if (obj.event === 'edit') {
            edit(obj);
        }
    });

    table.on('toolbar(user-table)', function (obj) {
        console.log(obj)
        if (obj.event === 'download') {
            download(obj);
        } else if (obj.event === 'refresh') {
            window.refresh();
        } else if (obj.event === 'batchRemove') {
            window.batchRemove(obj);
        }
    });

    // 查询表单提交
    form.on('submit(user-query)', function (data) {
        console.log("in query");
        console.log(data);
        // $.ajax({
        //     url:queryRegisterUrl,
        //     data:data.field,
        //     type:"GET",
        //     success : function (result) {
        //         if (result.code === succeedCode) {
        //             toast.success({title: 'Success', message: result.message, position: 'topCenter'});
        //             table.reload("user-table");
        //         } else {
        //             toast.error({title: 'Error', message: result.message, position: 'topCenter'});
        //         }
        //     }
        //     })
        table.reload('user-table', {
            url: queryRegisterUrl,
            where: data.field
        })
        return false;
    });

    // 编辑表单提交
    form.on("submit(editSubmit)", function (data) {
        // 得到所属的标准
        let selectedOption = document.getElementById('subtype').selectedOptions[0];
        let standard =  selectedOption.parentNode.getAttribute('data-group-value');
        data.field.standard = standard;
        $.ajax({
            url: updateRegisterUrl,
            dataType: 'json',
            data: data.field,
            type: 'POST',
            success: function (result) {
                if (result.code === succeedCode) {
                    layer.closeAll(); // 关闭页面
                    toast.success({title: 'Success', message: result.message, position: 'topCenter'});
                    table.reload("user-table");
                } else {
                    toast.error({title: 'Error', message: result.message, position: 'topCenter'});
                }
            }
        })
    })


    form.on('switch(user-enable)', function (obj) {
        layer.tips(this.value + ' ' + this.name + '：' + obj.elem.checked, obj.othis);
    });


    function edit(obj) {
        console.log("in edit");
        console.log(obj);
        // 表单数据回填
        $("#cid").val(obj.data.cid);
        $("#coverageId").val(obj.data.coverageId);
        $("#subtype").val(obj.data.subtype);
        $("#description").val(obj.data.description);
        form.render('select'); // 重新渲染 select，使 value 与显示值匹配
        layer.open({
            type: 1,
            title: '修改',
            shade: 0.1,
            area: ['500px', '400px'],
            content: $("#registerEdit")
        });
    }

    function remove(obj) {
        console.log("in remove");
        console.log(obj);
        layer.confirm('确定要删除该数据', {
            icon: 3,
            title: '提示'
        }, function (index) {
            layer.close(index);
            let loading = layer.load();
            $.ajax({
                url: deleteMetadataByIdUrl,
                dataType: 'json',
                data: {cid: obj.data['cid']},
                type: 'POST',
                success: function (result) {
                    layer.close(loading);
                    // 删除成功
                    if (result.code === succeedCode) {
                        layer.msg(result.message, {
                            icon: 1,
                            time: 500
                        }, function () {
                            obj.del();
                        });
                    } else {
                        // 删除失败
                        layer.msg(result.message, {
                            icon: 2,
                            time: 1000
                        });
                    }
                }
            })
        });
    }

    window.batchRemove = function (obj) {
        console.log("in batchRemove")

        let checkIds = common.checkField(obj, 'cid');
        console.log(checkIds);
        let delIds = {
            ids: checkIds
        }

        if (checkIds === "") {
            layer.msg("未选中数据", {
                icon: 3,
                time: 1000
            });
            return false;
        }

        layer.confirm('确定要删除这些数据', {
            icon: 3,
            title: '提示'
        }, function (index) {
            layer.close(index);
            let loading = layer.load();
            $.ajax({
                url: removeBatchUrl,
                dataType: 'json',
                type: 'POST',
                data: delIds,
                success: function (result) {
                    // layer.close(loading);
                    // if (result.success) {
                    //     layer.msg(result.msg, {
                    //         icon: 1,
                    //         time: 1000
                    //     }, function() {
                    //         table.reload('user-table');
                    //     });
                    // } else {
                    //     layer.msg(result.msg, {
                    //         icon: 2,
                    //         time: 1000
                    //     });
                    // }
                    layer.close(loading);
                    table.reloadData('user-table')
                }
            })
        });
    }

    window.refresh = function (param) {
        table.reload('user-table', {
            url: listRegisterUrl,
        })
    }

    // 改变验证状态
    form.on('switch(validate-enable)', function (data) {
        console.log("on switch");
        console.log(data);
        let elem = data.elem;
        // 是否开启验证
        let state;
        if (elem.checked) {
            state = 1;
        } else {
            state = 0;
        }

        $.ajax({
            url: changeValidateUrl,
            dataType: 'json',
            data: {"cid": elem.value, "validate": state},
            type: 'POST',
            success: function (result) {
                if (result.code === succeedCode) {
                    toast.success({title: 'Success', message: result.message, position: 'topCenter'});
                } else {
                    toast.error({title: 'Error', message: result.message, position: 'topCenter'});
                    elem.checked = !elem.checked;
                    table.reload("user-table");
                }
            }
        })
    });
})

function download(obj) {
    console.log("in download")

    let checkIds = common.checkField(obj, 'cid');
    console.log(typeof checkIds);
    if (checkIds === "") {
        toast.info({title: 'Info', message: "No data selected", position: 'topCenter'});
        return;
    }
    let downloadIds = {
        ids: checkIds
    };
    let downloadLink = document.createElement('a');
    downloadLink.href = downloadUrl + '?' + $.param(downloadIds);
    console.log(downloadLink.href);
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
}

